package com.example.activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.common.CheckConnection;
import com.example.demo.R;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncTaskGetDataPage extends ActionBarActivity {
	TextView txtResult, txtConnectionResult;
	ProgressBar proLoadData;
	Button btnStartLoadData;
	InputStream inStream;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_async_task_get_data_page);

		txtResult = (TextView) findViewById(R.id.txtStateResult);
		txtConnectionResult = (TextView) findViewById(R.id.txtConnectionResult);
		proLoadData = (ProgressBar) findViewById(R.id.progressLoadData);
		proLoadData.setVisibility(View.GONE);
		btnStartLoadData = (Button) findViewById(R.id.btnStartGetData);

		CheckConnection conCheck = new CheckConnection(
				AsyncTaskGetDataPage.this);
		if (conCheck.isConnected()) {
			txtConnectionResult.setText("you are connected to Internet");
			txtConnectionResult.setTextColor(Color.BLUE);
		} else {
			txtConnectionResult
					.setText("you are not connected to Internet! Try again later!");
			txtConnectionResult.setTextColor(Color.RED);
		}

		btnStartLoadData.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new AsyncGetData().execute("http://10.3.9.147:1337/user");
				// new AsyncGetData().execute(getResources().getString(
				// R.string.data_url));
			}
		});

	}

	public static String GET(String url) {
		InputStream inputStream = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
			inputStream = httpResponse.getEntity().getContent();
			if (inputStream != null) {
				result = convertInputStreamToString(inputStream);
			}
		} catch (Exception e) {
			Log.d("InputStream", e.getLocalizedMessage());
		}
		return result;
	}

	public static String convertInputStreamToString(InputStream inputStream) {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		String result = "";
		try {
			while ((line = bufferedReader.readLine()) != null) {
				result += line;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d("conver", "problem");
			e.printStackTrace();
		}
		try {
			bufferedReader.close();
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	private class AsyncGetData extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			proLoadData.setVisibility(View.VISIBLE);
			txtResult.setText("Loading data....!");
		}

		@Override
		protected String doInBackground(final String... URL) {
			// TODO Auto-generated method stub
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					// Toast.makeText(AsyncTaskGetDataPage.this, "" + URL[0],
					// 2000).show();
				}
			});
			return GET(URL[0]);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			txtResult.setText(values[0]);
		}

		@SuppressLint("NewApi")
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			proLoadData.setVisibility(View.GONE);
			JSONArray jaray = null, jarray1 = null;
			JSONObject json1 = null;
			String temp = "";
			String total = "";
			btnStartLoadData.setAlpha(0);
			btnStartLoadData.setClickable(false);
			try {
				jaray = new JSONArray(result);
				for (int i = 0; i < jaray.length(); i++) {
					temp = jaray.getJSONObject(i).toString();
					String id = jaray.getJSONObject(i).getString("id");
					String user = jaray.getJSONObject(i).getString("user");
					String createAt = jaray.getJSONObject(i).getString(
							"createdAt");
					String updateAt = jaray.getJSONObject(i).getString(
							"updatedAt");

					Object arr = jaray.getJSONObject(i).getJSONArray(
							"_dataSeries");
					total = total + " id: " + id + "\n user: " + user
							+ "\n createAt: " + createAt + "\n updateAt: "
							+ updateAt + "\n dataSerie: " + arr.toString();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				total = "problem, try again!" + "\n" + e.getMessage();
			}
			txtResult.setText("DONE!" + "\n" + total);
		}
	}

}
